import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import { getToken } from "@/utils/auth";
import { start, done } from "@/utils/nprogress";

const whiteList = ["/login", "/auth-redirect", "/bind", "/register", "/survey"];

router.beforeEach((to, from, next) => {
  console.log("🚀 ~ file: permission.js:10 ~ to, from, next:", to, from, next)
  // console.log(window.$wujie.props.token())
  start();
  console.log("🚀 ~ file: permission.js:13 ~ getToken:", getToken())
  if (getToken()) {
    
    if(to.matched && to.matched.length > 2) {
      to.matched.splice(1, to.matched.length - 2)
    }

    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
      done();
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch("GetInfo")
          .then((res) => {
            // 拉取user_info
            const roles = res.roles;
            store.dispatch("GenerateRoutes", { roles }).then((accessRoutes) => {
              // 测试 默认静态页面
              // store.dispatch('permission/generateRoutes', { roles }).then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes); // 动态添加可访问路由表
              // store.commit('SOCKET_SEND')

              next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
            });
          })
          .catch((err) => {
            store.dispatch("FedLogOut").then(() => {
              Message.error(err);
              next({ path: "/" });
            });
          });
      } else {
        console.log(1,'来了')
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      if (window.__POWERED_BY_WUJIE__&&window.$wujie.props&&window.$wujie.props.goLogin) {
        console.log("🚀 ~ file: permission.js:58 ~ window.$wujie.props:", window.$wujie)
        window.$wujie.props.goLogin();
      }
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`); // 否则全部重定向到登录页
      done();
    }
  }
});

router.afterEach(() => {
  done();
});
